package com.upc.toss.slice;

import com.upc.toss.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.TextField;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.eventhandler.InnerEvent;
import okhttp3.*;
import org.json.JSONObject;

public class AddAbilitySlice extends AbilitySlice {

    TextField textFieldEquipmentId;
    TextField textFieldEquipmentName;
    String equipmentId;
    String equipmentName;
    Text text;
    MyEventHandler handler;
    String username;
    Preferences preferences;

    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_add);

        username = intent.getStringParam("name");
        EventRunner runner = EventRunner.current();
        handler = new MyEventHandler(runner);
//        DatabaseHelper databaseHelper = new DatabaseHelper(this); // context入参类型为ohos.app.Context。
//        preferences = databaseHelper.getPreferences("user");

//        username = preferences.getString("username","");
        textFieldEquipmentId = (TextField) findComponentById(ResourceTable.Id_textField_equipment_id);
        textFieldEquipmentName = (TextField) findComponentById(ResourceTable.Id_textField_equipment_name);
        Button btnAdd = (Button) findComponentById(ResourceTable.Id_btn_add);

        btnAdd.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if(textFieldEquipmentId.getText().length()<1||textFieldEquipmentName.getText().length()<1){
                    new ToastDialog(AddAbilitySlice.this).setText("请将信息填写完整")
                            .setAlignment(LayoutAlignment.TOP)
                            .show();
                }
                else {
                    equipmentId = textFieldEquipmentId.getText().toString();
                    equipmentName = textFieldEquipmentName.getText().toString();

                    AddDeviceThread addDeviceThread = new AddDeviceThread();
                    addDeviceThread.start();

//                    setResult(intent);
                    terminate();
                }
            }
        });
    }


    public class AddDeviceThread extends Thread {
        public void run() {
            try {
                String json = "{\"username\":\"" + username + "\",\"deviceId\":\"" + equipmentId + "\",\"name\":\"" + equipmentName + "\"}";
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .url("http://1.116.33.97:8080/addDevice")
                        .post(RequestBody.create(MediaType.parse("application/json"), json))
                        .build();
                Response response = client.newCall(request).execute();
                String responseData = response.body().string();
                JSONObject jsonObject = new JSONObject(responseData);
                int code = (int) jsonObject.get("code");
                if(code==100){
                    handler.sendEvent(1);
                }else{
                    handler.sendEvent(2);

                }

            } catch (Exception e) {
                e.printStackTrace();
                new ToastDialog(getContext()).setText("网络连接超时").setAlignment(LayoutAlignment.TOP).show();
            }
        }
    }

    private class MyEventHandler extends EventHandler {
        private MyEventHandler(EventRunner runner) {
            super(runner);
        }
        // 重写实现processEvent方法
        @Override
        public void processEvent(InnerEvent event) {
            super.processEvent(event);
            if (event == null) {
                return;
            }
            int eventId = event.eventId;
            switch (eventId) {
                case 1:
                    new ToastDialog(getContext()).setText("成功!").setAlignment(LayoutAlignment.TOP).show();
                    terminate();        //结束当前页面
                    break;
                case 2:
                    new ToastDialog(getContext()).setText("失败!").setAlignment(LayoutAlignment.TOP).show();
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

}
